import { ref, watchEffect } from "vue";

export function useDarkMode() {
    // 从 localStorage 获取初始值，如果没有则默认为 false
    const isDark = ref<boolean>(localStorage.getItem("darkMode") === "true");

    // 使用 watchEffect 来监听 isDark 的变化
    watchEffect(() => {
        // 更新 DOM 的 class
        document.documentElement.classList.toggle("dark", isDark.value);
        // 保存到 localStorage
        localStorage.setItem("darkMode", String(isDark.value));
    });

    // 切换暗黑模式的函数
    const toggleDarkMode = () => {
        isDark.value = !isDark.value;
    };

    // 初始化时立即应用主题
    document.documentElement.classList.toggle("dark", isDark.value);

    return { isDark, toggleDarkMode };
}
